import Footer from '@/components/Footer';
import { userLogin } from '@/services/backend/userController';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText, ProFormCheckbox } from '@ant-design/pro-components';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { Helmet, history, useModel } from '@umijs/max';
import { message } from 'antd';
import React, { useState, useEffect } from 'react';
import Settings from '../../../../config/defaultSettings';
import { motion } from 'framer-motion';

import './index.css';
import { encrypt } from '@/pages/utils/jsencrypt';

const Login: React.FC = () => {
  const [type] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const [loading, setLoading] = useState<boolean>(false);
  const [rememberMe, setRememberMe] = useState<boolean>(
    localStorage.getItem('rememberMe') === 'true',
  );

  const [particles, setParticles] = useState<
    Array<{ x: number; y: number; size: number; speed: number }>
  >([]);

  // 页面加载时检查是否有保存的登录信息
  useEffect(() => {
    if (localStorage.getItem('rememberMe') === 'true') {
      const savedAccount = localStorage.getItem('userAccount');
      if (savedAccount) {
        // 如果有保存的账号，可以自动填充表单
        const loginForm = document.querySelector('form');
        if (loginForm) {
          const accountInput = loginForm.querySelector(
            'input[name="userAccount"]',
          ) as HTMLInputElement;
          if (accountInput) {
            accountInput.value = savedAccount;
          }
        }
      }
    }
  }, []);

  useEffect(() => {
    const particlesArray = Array.from({ length: 50 }, () => ({
      x: Math.random() * window.innerWidth,
      y: Math.random() * window.innerHeight,
      size: Math.random() * 3 + 1,
      speed: Math.random() * 1 + 0.5,
    }));
    setParticles(particlesArray);

    const interval = setInterval(() => {
      setParticles((prev) =>
        prev.map((p) => ({
          ...p,
          y: p.y + p.speed > window.innerHeight ? 0 : p.y + p.speed,
        })),
      );
    }, 50);

    return () => clearInterval(interval);
  }, []);

  const containerClassName = useEmotionCss(() => {
    return {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage: 'url(/background.jpg)',
      backgroundSize: '100% 100%',
      position: 'relative',
    };
  });

  const handleSubmit = async (values: API.UserLoginRequest & { rememberMe?: boolean }) => {
    try {
      setLoading(true);
      // 登录
      if (!values.userAccount || !values.userPassword) {
        message.error('用户名和密码不能为空');
        setLoading(false);
        return;
      }

      // 保存记住我的状态
      localStorage.setItem('rememberMe', values.rememberMe ? 'true' : 'false');

      // 如果选择了记住我，保存账号
      if (values.rememberMe) {
        localStorage.setItem('userAccount', values.userAccount);
      } else {
        localStorage.removeItem('userAccount');
      }

      const encryptPassword = encrypt(values.userPassword);
      const res = await userLogin({
        userAccount: values.userAccount,
        userPassword: encryptPassword as string,
        rememberMe: values.rememberMe,
      });

      const defaultLoginSuccessMessage = '登录成功！';
      message.success(defaultLoginSuccessMessage);
      // 保存已登录用户信息
      setInitialState({
        ...initialState,
        currentUser: res.data,
      });

      // 直接跳转到聊天页面
      history.push('/chat');
      return;
    } catch (error: any) {
      const defaultLoginFailureMessage = `登录失败，${error.message}`;
      message.error(defaultLoginFailureMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      className={containerClassName}
      style={{
        padding: '32px 0',
      }}
    >
      <Helmet>
        <title>
          {'登录'}- {Settings.title}
        </title>
      </Helmet>

      {particles.map((particle, index) => (
        <div
          key={index}
          className="particle"
          style={{
            position: 'fixed',
            left: particle.x,
            top: particle.y,
            width: particle.size,
            height: particle.size,
            backgroundColor: 'rgba(77, 166, 255, 0.7)',
            borderRadius: '50%',
            pointerEvents: 'none',
            zIndex: 1,
          }}
        />
      ))}

      <div
        style={{
          flex: '1',
          padding: '32px 0',
          display: 'flex',
          justifyContent: 'flex-end',
          alignItems: 'center',
          overflow: 'hidden',
        }}
      >
        <div
          style={{
            flex: '0 0 auto',
            padding: '32px 80px 32px 0',
            overflow: 'hidden',
          }}
        >
          <div style={{ position: 'absolute', top: 0, left: 0, margin: '16px' }}>
            <img alt="logo" style={{ height: '40px' }} src="/dynabook.png" />
          </div>

          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8 }}
          >
            <div className="tech-login-container">
              <div className="tech-login-box">
                <div className="tech-login-header">
                  <h2>Knowledge</h2>
                  <div className="tech-login-line"></div>
                </div>

                <LoginForm
                  contentStyle={{
                    minWidth: 280,
                    maxWidth: '75vw',
                    background: 'transparent',
                  }}
                  initialValues={{
                    autoLogin: true,
                    rememberMe: localStorage.getItem('rememberMe') === 'true',
                  }}
                  submitter={{
                    searchConfig: {
                      submitText: '登录',
                    },
                    submitButtonProps: {
                      loading: loading,
                      className: 'tech-login-button',
                    },
                  }}
                  onFinish={async (values) => {
                    await handleSubmit(values as API.UserLoginRequest & { rememberMe?: boolean });
                  }}
                >
                  {type === 'account' && (
                    <>
                      <ProFormText
                        name="userAccount"
                        fieldProps={{
                          size: 'large',
                          prefix: <UserOutlined className="tech-icon" />,
                          className: 'tech-input',
                        }}
                        placeholder={'请输入账号'}
                        rules={[
                          {
                            required: true,
                            message: '账号不能为空!',
                          },
                        ]}
                      />
                      <ProFormText.Password
                        name="userPassword"
                        fieldProps={{
                          size: 'large',
                          prefix: <LockOutlined className="tech-icon" />,
                          className: 'tech-input',
                        }}
                        placeholder={'请输入密码'}
                        rules={[
                          {
                            required: true,
                            message: '密码不能为空!',
                          },
                        ]}
                      />
                      <ProFormCheckbox name="rememberMe" className="remember-me-checkbox">
                        <span className="remember-me-text">记住我</span>
                      </ProFormCheckbox>
                    </>
                  )}
                  {/* 
                  <div
                    style={{
                      float: 'right',
                    }}
                  >
                    <Link to="/user/register">新用户注册</Link>
                  </div> */}
                </LoginForm>
              </div>
            </div>
          </motion.div>
        </div>
      </div>
      <Footer />
    </div>
  );
};
export default Login;
